package HomeService

import (
	"context"
	"gdshop-font-api-go/app/entity"
	"gdshop-font-api-go/app/request/HomeReq"
	"gdshop-font-api-go/app/response/HomeResp"
	"gdshop-font-api-go/library/response"
	"gdshop-font-api-go/library/tools"
	toolsDb "gdshop-font-api-go/library/tools/db"
	toolsJwt "gdshop-font-api-go/library/tools/jwt"
	"gdshop-font-api-go/library/wxpayHelper"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/shenghui0779/gochat/oa"
	"time"
)

func WechatLogin(ctx context.Context, parames *HomeReq.WechatLogin) *response.JsonResponse {
	wxoa := wxpayHelper.GetWxOa()
	token, err := wxoa.Code2AuthToken(ctx, parames.Code)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	wechatInfo, err := wxpayHelper.GetAuthUser(ctx, token.AccessToken, token.OpenID)
	if err != nil {
		return response.FailByRequestMessage(nil, "获取用户信息失败："+err.Error())
	}

	return WechatLoginByAuthUser(ctx, token.OpenID, wechatInfo)
}

func WechatLoginByAuthUser(ctx context.Context, openid string, wechatInfo *oa.AuthUser) *response.JsonResponse {
	var mwModel *entity.MemberWechat
	err := toolsDb.GetUnSafaTable(ctx, "member_wechat").Where("openid", openid).
		Scan(&mwModel)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	var memberId int64 = 0
	nickName := tools.UnicodeEmojiCode(wechatInfo.Nickname)
	err = g.DB().Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
		if mwModel != nil {
			if mwModel.MemberId < 1 {
				// 不存在会员
				memberId, err = addMember(tx, nickName, wechatInfo.HeadImgURL)
				if err != nil {
					return err
				}
			} else {
				memberId = int64(mwModel.MemberId)
			}

			_, err := tx.Model("member_wechat").Unscoped().
				Where("id", mwModel.Id).Update(g.Map{
				"member_id": memberId,
				"nickname":  nickName,
				"gender":    wechatInfo.Sex,
				"avatar":    wechatInfo.HeadImgURL,
				"country":   wechatInfo.Country,
				"province":  wechatInfo.Province,
				"city":      wechatInfo.City,
			})
			if err != nil {
				return err
			}
		} else {
			memberId, err = addMember(tx, nickName, wechatInfo.HeadImgURL)
			if err != nil {
				return err
			}

			// 没有数据
			_, err = tx.Model("member_wechat").Unscoped().InsertAndGetId(g.Map{
				"member_id": memberId,
				"openid":    wechatInfo.OpenID,
				"nickname":  nickName,
				"gender":    wechatInfo.Sex,
				"avatar":    wechatInfo.HeadImgURL,
				"country":   wechatInfo.Country,
				"province":  wechatInfo.Province,
				"city":      wechatInfo.City,
			})
			if err != nil {
				return err
			}
		}

		return nil
	})
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	// 如果没有错误，进行登陆
	resp := new(HomeResp.Login)
	resp.Id = uint(memberId)
	resp.Nickname = nickName
	resp.Avatar = wechatInfo.HeadImgURL

	tokenString, err := toolsJwt.GenerateLoginToken(resp.Id, nickName)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	resp.Token = tokenString

	// 写登陆日志
	//LogService.MemberLoginLog(memberModel)

	return response.SuccessByRequestMessageData(nil, "成功", resp)
}

func addMember(tx *gdb.TX, nickName, avatar string) (int64, error) {
	return tx.Model("member").Unscoped().InsertAndGetId(g.Map{
		"nickname":  nickName,
		"avatar":    avatar,
		"status":    1,
		"create_at": time.Now().Unix(),
	})
}
